/*
 * Copyright 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.chatty.compose.screens.conversation

import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocal
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import androidx.compose.ui.zIndex
import kotlinx.coroutines.launch

/**
 * This [Composable] can be used with a [LocalBackPressedDispatcher] to intercept a back press.
 *
 * @param onBackPressed (Event) What to do when back is intercepted
 *
 */
@Composable
fun BackPressHandler(onBackPressed: () -> Unit) {
    // Safely update the current `onBack` lambda when a new one is provided
    val currentOnBackPressed by rememberUpdatedState(onBackPressed)

    // Remember in Composition a back callback that calls the `onBackPressed` lambda
    val backCallback = remember {
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                currentOnBackPressed()
            }
        }
    }

    val backDispatcher = LocalBackPressedDispatcher.current

    // Whenever there's a new dispatcher set up the callback
    DisposableEffect(backDispatcher) {
        backDispatcher.addCallback(backCallback)
        // When the effect leaves the Composition, or there's a new dispatcher, remove the callback
        onDispose {
            backCallback.remove()
        }
    }
}

/**
 * This [CompositionLocal] is used to provide an [OnBackPressedDispatcher]:
 *
 * ```
 * CompositionLocalProvider(
 *     LocalBackPressedDispatcher provides requireActivity().onBackPressedDispatcher
 * ) { }
 * ```
 *
 * and setting up the callbacks with [BackPressHandler].
 */
val LocalBackPressedDispatcher =
    staticCompositionLocalOf<OnBackPressedDispatcher> { error("No Back Dispatcher provided") }


// 定义职位数据类
data class JobPost(
    val title: String,
    val company: String,
    val salary: String,
    val experience: String,
    val education: String,
    val contact: String,
    val location: String
)

@Composable
fun JobPostCard(job: JobPost) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        shape = RoundedCornerShape(8.dp),
        elevation = 4.dp
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = job.title,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                )
                Box(
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .size(20.dp)
                        .background(Color.LightGray, RoundedCornerShape(2.dp)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "猎",
                        color = Color.White,
                        fontSize = 12.sp
                    )
                }
                Spacer(modifier = Modifier.weight(1F))
                Text(
                    text = job.salary,
                    fontSize = 16.sp,
                    color = Color(0xFF007AFF)
                )
            }
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = job.company,
                fontSize = 14.sp,
                color = Color.Gray,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Spacer(modifier = Modifier.height(8.dp))
            Row {
                Box(
                    modifier = Modifier
                        .background(Color.Gray, RoundedCornerShape(4.dp))
                        .padding(start = 4.dp, top = 2.dp, bottom = 2.dp, end = 4.dp)
                ) {
                    Text(
                        text = job.experience,
                        fontSize = 12.sp,
                        color = Color.DarkGray
                    )
                }
                Spacer(modifier = Modifier.width(4.dp))
                Box(
                    modifier = Modifier
                        .background(Color.Gray, RoundedCornerShape(4.dp))
                        .padding(2.dp)
                ) {
                    Text(
                        text = job.education,
                        fontSize = 12.sp,
                        color = Color.DarkGray
                    )
                }
                Spacer(modifier = Modifier.width(4.dp))
                Box(
                    modifier = Modifier
                        .background(Color.Gray, RoundedCornerShape(4.dp))
                        .padding(2.dp)
                ) {
                    Text(
                        text = job.contact,
                        fontSize = 12.sp,
                        color = Color.DarkGray
                    )
                }
            }
            Spacer(modifier = Modifier.height(8.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    painter = painterResource(id = android.R.drawable.ic_menu_always_landscape_portrait),
                    contentDescription = "Location",
                    tint = Color.Gray,
                    modifier = Modifier
                        .size(24.dp)
                        .clip(CircleShape)
                        .background(Color.LightGray)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Column {
                    Text(
                        text = job.location,
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                    Spacer(modifier = Modifier.height(2.dp))
                    Text(
                        text = job.location,
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                }

                Spacer(modifier = Modifier.weight(1F))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = job.location,
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Icon(
                        imageVector = Icons.Filled.Close,
                        contentDescription = "Close",
                        tint = Color.Gray, modifier = Modifier.size(16.dp)
                    )
                }

            }
        }
    }
}

@Composable
fun JobPostList() {
    val jobPosts = listOf(
        JobPost(
            title = "安卓开发",
            company = "某大型汽车研发/制造公司",
            salary = "20-40K",
            experience = "5-10年",
            education = "本科",
            contact = "刘先生·猎头顾问",
            location = "上海"
        ),
        JobPost(
            title = "安卓开发",
            company = "中国某中型金融科技公司",
            salary = "30-50K·13薪",
            experience = "5-10年",
            education = "本科",
            contact = "汪女士·猎头顾问",
            location = "上海"
        ),
        JobPost(
            title = "Android系统开发工程师",
            company = "上海亚阔信息",
            salary = "25-40K",
            experience = "经验不限",
            education = "学历不限",
            contact = "金先生·hrbp",
            location = "上海"
        )
    )
    LazyColumn(
        verticalArrangement = Arrangement.spacedBy(4.dp),
        modifier = Modifier.fillMaxWidth()
    ) {
        items(jobPosts.size) { index ->
            JobPostCard(job = jobPosts[index])
        }
    }
}


@Composable
fun ProductListScreen() {
    // 控制弹窗的显示与隐藏
    var showPopup by remember { mutableStateOf(false) }

    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        // 商品列表
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            ProductList()
        }

        // 按钮
        Button(
            onClick = { showPopup = true },
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp)
        ) {
            Text("显示底部弹窗")
        }
// 蒙层
        if (showPopup) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.5f)) // 半透明黑色蒙层
                    .zIndex(1f) // 确保蒙层在弹窗下方
            )
        }
        // 弹窗
        if (showPopup) {
            Popup(
                alignment = Alignment.BottomCenter, // 弹窗在底部居中
                onDismissRequest = { showPopup = false }, // 点击外部关闭弹窗
                properties = PopupProperties(focusable = true) // 允许弹窗获取焦点
            ) {
                // 弹窗内容

                    Column(
                        modifier = Modifier.background(Color.White).padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text("这是底部弹窗的内容")
                        Spacer(modifier = Modifier.height(16.dp))
                        Button(
                            onClick = { showPopup = false },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text("关闭弹窗")
                        }
                    }

            }
        }
    }
}

@Composable
fun ProductList() {
    // 模拟商品列表
    Column {
        repeat(10) { index ->
            Text("商品 ${index + 1}", modifier = Modifier.padding(8.dp))
        }
    }
}


@Preview(showBackground = true)
@Composable
fun JobPostListPreview() {
    //JobPostList()
    //ProductList()
    ProductListScreen()
}

